import { defineStore } from "pinia";
import SockJS from "sockjs-client";
import Stomp from "stompjs";

interface SockTask {
  topic: string;
  callback: () => {};
}

export const useSocketStore = defineStore("socketStore", () => {
  const url = ref("");
  const header = ref<object>();
  const checkInterval = ref<NodeJS.Timeout>();
  const websocket = ref<WebSocket>();
  const stompClient = ref<Stomp.Client>();
  const listenerList = ref<SockTask[]>([]);

  const init = (wsUrl: string, wsHeader: object = {}) => {
    if (stompClient.value?.connected) {
      console.log("websocket: already connected");
      return;
    }
    url.value = wsUrl;
    header.value = wsHeader;
    if (!stompClient.value) {
      connect();
      return;
    }
    if (websocket.value?.readyState === SockJS.OPEN) {
      stompClient.value.disconnect(() => {
        connect();
      });
    } else if (websocket.value?.readyState === SockJS.CONNECTING) {
      console.log("websocket: connecting");
      return;
    } else {
      connect();
    }
  };

  const connect = () => {
    websocket.value = new SockJS(url.value);
    stompClient.value = Stomp.over(websocket.value);
    stompClient.value.debug = () => {}; // 关闭打印
    // 发起连接
    stompClient.value.connect(
      header.value!,
      (_success) => {
        console.log("websocket: successfully connected");
        listenerList.value.forEach((item) => {
          stompClient.value?.subscribe(item.topic, item.callback);
        });
      },
      (_err) => {
        setTimeout(() => {
          init(url.value);
        }, 500);
      }
    );
  };
});
